﻿EUI.BatchImportView = EUI.extend(EUI.CustomUI, {
    renderTo: "",
    iframeId: "orderBody",
    initComponent: function () {
        var g = this;
        EUI.Container({
            renderTo: this.renderTo,
            // layout: "border",
            border: false,
            //padding: 8,
            itemspace: 10,
            items: [{
                xtype: "Button",
                title: "导入",
                handler: function () {
                    g.batchWin();
                }
            }, {
                xtype: "Button",
                title: "导出",
                handler: function () {
                    window.location.href = _ctxPath + "/file/BatchExport";
                }
            }]
        });
    },
    batchWin: function (headfrmdata) {
        var g = this;
        g.lastsel2 = "";
        g.batchgrid = EUI.BatchImport({
            width: 800,
            title: "批量导入",
            params: headfrmdata,
            templateUrl: _ctxPath + "/file/downloadTemplate",  //模板下载url downloadTemplate
            url: _ctxPath + "/file/BatchImport",
            afterLoad: function (data) {
                if (data.operateStatus.success) {
                    for (var i = 0, len = data.items.length; i < len; i++) {
                        var item = data.items[i];
                        item.id = MyUtils.uuid.newUuid();
                        item.status = 1;
                        item.applyMoney = parseFloat(item.applyMoney);
                        g.setStatus(item.id, item);
                    }
                    g.batchgrid.gridList.setDataInGrid(data.items);
                } else {
                    EUI.ProcessStatus({
                        success: false,
                        title: "温馨提示",
                        msg: data.operateStatus.msg,
                    });
                }


            },
            confirm: function (itemDatas) {
                var msg = "";
                if (itemDatas) {
                    for (var i = 0; i < itemDatas.length; i++) {
                        var item = itemDatas[i];
                        if (!~~item.status) {
                            if (isNaN(parseFloat(item.applyMoney))) {
                                msg = "导入数据第" + (i + 1) + "行中的列【申请金额】有误";
                                break;
                            }
                            if (isNaN(parseFloat(item.budgetApplyMoney))) {
                                msg = "导入数据第" + (i + 1) + "行中的列【已维护预算】有误";
                                break;
                            }
                            if (new Date(item.startDate) == "Invalid Date") {
                                msg = "导入数据第" + (i + 1) + "行中的列【有效起始日期】有误";
                            }
                        }
                    }
                }
                if (msg) {
                    g.message(msg);
                    return false;
                }
                return true;
                // var data = batchgrid.gridList.getGridData(), err = 0;
                // if (data.length > 0) {
                //     for (var i = 0; i < data.length; i++) {
                //         if (data[i].GenerateError == "true" || data[i].GenerateError === true) {
                //             err++;
                //         }
                //     }
                //     if (err != 0) {
                //         //-*-BRM100272=操作提示；BRM101595=列表中含有未验证通过的项；
                //         g.msgAlert(SEI.lang("BRM100272"), SEI.lang("BRM101595"));
                //         return false;
                //     } else {
                //         g.colsData = [];
                //         for (var idx = 0; idx < g.batchColsData.length; idx++) {
                //             var colName = g.batchColsData[idx];
                //             if (colName.name.indexOf("GenerateError") < 0) {
                //                 g.colsData.push(g.batchColsData[idx]);
                //             }
                //         }
                //         !g.requestItem && g.initRequestItem();
                //         var requestItems = g.requestItem.getGridData();
                //         g.requestItem.setDataInGrid(requestItems.concat(data));
                //         g.setSumMoney();
                //         $('div.e-directory[targetctn="requestitembox"]').click();
                //     }
                // } else {
                //     //-*-BRM100272=操作提示；BRM101596=列表中没有需要导入的项；
                //     g.msgAlert(SEI.lang("BRM100272"), SEI.lang("BRM101596"));
                //     return false;
                // }
            },
            gridCfg: {
                loadonce: true,
                datatype: "local",
                rowNum: 15,
                shrinkToFit: false,
                colModel: [{name: 'id', hidden: true},
                    {name: 'requestId', hidden: true},
                    {name: 'status', hidden: true},
                    {name: 'statusStr', index: 'status', label: "数据有效性", align: "center", width: 80},
                    {name: 'displayNumber', index: "displayNumber", label: "编号", width: 85},
                    {name: 'startDate', index: 'startDate', label: "有效起始日期", width: 90,editable: true,},
                    {
                        name: 'budgetApplyMoney',
                        index: 'budgetApplyMoney',
                        editable: true,
                        sortable: false,
                        formatter: 'currency',
                        formatoptions: {decimalSeparator: ".", thousandsSeparator: " ", decimalPlaces: 2},
                        label: "已维护预算",
                        align: "right",
                        width: 90,
                        editrules: {number: true}
                    },
                    {
                        name: 'applyMoney',
                        index: 'applyMoney',
                        formatter: 'currency',
                        formatoptions: {decimalSeparator: ".", thousandsSeparator: " ", decimalPlaces: 2},
                        label: "申请金额",
                        align: "right",
                        classes: "gridcelleditable",
                        sorttype: 'number',
                        editrules: {number: true, minValue: -9999999999, maxValue: 9999999999},
                        editable: true,
                        width: 90
                    },
                    {
                        name: 'itemNote',
                        index: 'itemNote',
                        label: "备注说明",
                        classes: "gridcelleditable",
                        sortable: false,
                        width: 120
                    },
                    {
                        name: 'stock',
                        index: 'stock',
                        width: 60,
                        editable: true,
                        edittype: "checkbox",
                        editoptions: {value: "TRUE:FALSE"}
                    },
                ],
                /*onSelectRow : function(id) {
                 if (id && id !== g.lastsel2) {

                 g.batchgrid.gridList.grid.jqGrid('restoreRow', g.lastsel2);
                 g.batchgrid.gridList.grid.jqGrid('editRow', id, true);
                 g.lastsel2 = id;
                 }
                 },*/
                /*        localReader: { id: "d" },*/
                cellEdit: true,
                cellsubmit: 'clientArray',
                afterEditCell: function (id, name, val, iRow, iCol) {
                    console.log("afterEditCell");
                    /*if (name == 'invdate') {
                        jQuery("#" + iRow + "_invdate", "#celltbl").datepicker({dateFormat: "yy-mm-dd"});
                    }*/
                },
                afterSaveCell: function (rowid, name, val, iRow, iCol) {
                    g.setStatus(rowid);
                  /*  if (name == 'amount') {
                        var taxval = jQuery("#celltbl").jqGrid('getCell', rowid, iCol + 1);
                        jQuery("#celltbl").jqGrid('setRowData', rowid, {
                            total: parseFloat(val) + parseFloat(taxval)
                        });
                    }
                    if (name == 'tax') {
                        var amtval = jQuery("#celltbl").jqGrid('getCell', rowid, iCol - 1);
                        jQuery("#celltbl").jqGrid('setRowData', rowid, {total: parseFloat(val) + parseFloat(amtval)});
                    }*/
                }
            }
        });
    },
    setStatus: function (rowId, rowData) {
        var isEditRow = !rowData;
        if(isEditRow){
            rowData = this.batchgrid.gridList.grid.getRowData(rowId);
        }
        if (isNaN(parseFloat(rowData.applyMoney))) {
            rowData.applyMoney = 0;
        }
        rowData.budgetApplyMoney = parseFloat(rowData.budgetApplyMoney);
        if (isNaN(parseFloat(rowData.budgetApplyMoney))) {
            rowData.budgetApplyMoney = 0;
        }
        if (new Date(rowData.startDate) == "Invalid Date") {
            rowData.status = 0;
        }
        if (rowData.status) {
            rowData.statusStr = "<span style='color:green;font-size:20px;height:20px;line-height:20px;' title='检查通过'>√</span>";
        } else {
            rowData.statusStr = "<span style='color:red;font-size:20px;height:20px;line-height:20px;' title='检查失败'>X</span>";
        }

        if(isEditRow){
            this.batchgrid.gridList.grid.setRowData(rowId, { statusStr: rowData.statusStr });
        }
      /*  var rows = gridCmp.getGridData();
        for (var i = 0; i < rows.length; i++) {
            var row = rows[i];
            var rspan1 = "<span style='color:red;font-size:30px;height:20px;line-height:20px;' title='检查失败'>X</span>";
            var rspan2 = "<span style='color:green;font-size:30px;height:20px;line-height:20px;' title='检查通过'>√</span>";
            switch (row.Status.toString()) {
                case "0":
                    gridCmp.grid.setRowData(row.Id, { StatusStr: rspan1 });
                    break;
                case "1":
                    gridCmp.grid.setRowData(row.Id, { StatusStr: rspan2 });
                    break;
                default:
            }
        }*/
    },
    message: function (msg) {
        EUI.ProcessStatus({
            success: false,
            title: "温馨提示",
            msg: msg,
        });
    }
});


EUI.BatchImport = function () {
    var instance = new EUI.file.BatchImport(arguments[0]);
    window[instance.timestamp] = instance;
    return instance;
};
EUI.file.BatchImport = function () {
    EUI.apply(this, arguments[0]);
    this.initComponent();
};
EUI.apply(EUI.file.BatchImport.prototype, {
    url: "",
    params: null,
    width: 500,
    height: 300,
    beforeClose: null,
    confirm: null,
    afterLoad: null,
    templateUrl: "",  //模板下载url downloadTemplate
    templateDownload: "模板下载",
    timestamp: "timestamp_" + new Date().getTime(),
    initComponent: function () {
        var g = this;
        g.win = EUI.Window({
            title: g.title,
            width: g.width,
            height: g.height,
            buttonAlign: "center",
            buttons: g.initToolBar(),
            items: [{
                xtype: "GridPanel",
                tbar: g.initGridBar(),
                showSearch: false,
                border: true,
                gridCfg: g.gridCfg
            }],
            afterClose: function () {
                g.remove();
            }
        });
        g.gridList = EUI.getCmp(g.win.items[0]);
        g.initUrl();
        g.initUploadDom();
    },
    initUrl: function () {
        var g = this;
        if (!g.params) {
            return;
        }
        var flag = false;
        for (var key in g.params) {
            if (flag) {
                g.url += "&" + key + "=" + g.params[key];
            } else {
                g.url += "?" + key + "=" + g.params[key];
                flag = true;
            }
        }
    },
    initUploadDom: function () {
        var g = this;
        var iframe = $("<iframe style='display:none;'></iframe>");
        iframe.appendTo("body");
        g.mask = EUI.LoadMask({msg: "upload"});//initUploadMsg
        g.mask.hide();
        //兼容谷歌浏览器
        if ($.browser.chrome) {//火狐mozilla
            iframe.attr("src", "#");
        }
        iframe.bind("load", function () {
            var form = $("<form enctype='multipart/form-data' action='" + g.url + "' method='post'><input name='timestamp' type='text' value='" + g.timestamp + "'/></form>");
            g.input = $("<input name='file' type='file'/>").bind("change", function () {
                g.mask.show();
                form.submit();
            });
            form.append(g.input);
            iframe.contents().find("body").append(form);
            g.iframe = iframe;
        });
    },
    getResponse: function (data) {
        this.mask.hide();
        this.afterLoad && this.afterLoad(data);
    },
    initToolBar: function () {
        var g = this;
        return [{
            title: "确认",
            // width: 50,
            handler: function () {
                if (g.confirm) {
                    var data = g.gridList.getGridData();
                    var result = g.confirm(data);
                    if (!result) {
                        return;
                    }
                }
                g.win.close();
            }
        }, {
            title: "取消",
            // width: 50,
            handler: function () {
                g.win.close();
            }
        }];
    },
    initGridBar: function () {
        var g = this;
        var bar = [{
            title: "选择文件",
            handler: function () {
                g.iframe.contents().find("input").click();
            }
        }, {
            title: "删除",
            handler: function () {
                var row = g.gridList.getSelectRow();
                if (row.id) {
                    var infoBox = EUI.MessageBox({
                        title: "提示",
                        msg: "您确定要删除吗？",
                        buttons: [{
                            title: "确定",
                            selected: true,
                            handler: function handler() {
                                infoBox.remove();
                                g.gridList.grid.delRowData(row.id);
                            }
                        }, {
                            title: "取消",
                            handler: function handler() {
                                infoBox.remove();
                            }
                        }]
                    });
                } else {
                    EUI.ProcessStatus({
                        success: false,
                        title: "温馨提示",
                        msg: "请选择要删除的行",
                    });
                }
            }
        }];
        if (g.templateUrl) {
            bar.push("->");
            bar.push({
                title: g.templateDownload,
                handler: function () {
                    window.location.href = g.templateUrl;
                }
            });
        }
        return bar;
    },
    remove: function () {
        this.iframe.remove();
    }
});